package com.fmjava.service_video.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fmjava.service_video.entity.Category;
import com.fmjava.service_video.entity.excel.CategoryData;
import com.fmjava.service_video.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*
 *@ClassName ExcelListener
 *@Description TODO
 *@Author 吃麻椒的花酱
 *@Date 2021/7/12 11:23
 *@Version 1.0
 */
@Component
public class ExcelListener extends AnalysisEventListener<CategoryData> {
    @Autowired
    CategoryService categoryService;
    /*一行一行读取数据,读取一行就调用*/
    @Override
    public void invoke(CategoryData categoryData, AnalysisContext analysisContext) {
        Category oneCategory = this.oneCateCategory(categoryData);
        //一级分类不存在 插入一级分类
        if (oneCategory == null) {
            oneCategory = new Category();
            oneCategory.setTitle(categoryData.getOneCategoryData());
            oneCategory.setParentId("0");
            categoryService.save(oneCategory);
        }

        Category twoCategory = this.twoCateCategory(categoryData, oneCategory.getId());
        if (twoCategory == null) {
             twoCategory = new Category();
             twoCategory.setTitle(categoryData.getTowCategoryData());
             twoCategory.setParentId(oneCategory.getId());
             categoryService.save(twoCategory);
        }
    }

    /*
     * @author 吃麻椒的花酱
     * @date  2021/7/12 14:26
     * @Description 查询一级分类
     * @param categoryData
     * @return com.fmjava.service_video.entity.Category
     */
    public Category oneCateCategory(CategoryData categoryData){
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("title",categoryData.getOneCategoryData());
        //0表示一级分类
        categoryQueryWrapper.eq("parent_id",0);
        Category one = categoryService.getOne(categoryQueryWrapper);
        return one;

    }

    /*
     * @author 吃麻椒的花酱
     * @date  2021/7/12 14:32
     * @Description 查询二级分类
     * @param categoryData
     * @param pid
     * @return com.fmjava.service_video.entity.Category
     */
    public Category twoCateCategory(CategoryData categoryData,String pid){
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("title",categoryData.getTowCategoryData());
        //pid表示 父级分类 就是父级分类的主键
        categoryQueryWrapper.eq("parent_id",pid);
        Category two = categoryService.getOne(categoryQueryWrapper);
        return two;

    }


    /*全部读取完后会自动调用*/
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
